﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SoldierController : MonoBehaviour {

    public static int SPEED = 9;
    public static int JUMP = 25;
    public static float JUMP_DURATION = .3f;

    public bool controlled;

    private Rigidbody2D r;

    private GameController gameController;

    private JumpDetectionComponent jumpDetection;

    private float jumpJuice = JUMP_DURATION;

    private bool victory = false;

    void Start()
    {
        r = GetComponent<Rigidbody2D>();
        gameController = GameObject.Find("Game").GetComponent<GameController>();
        jumpDetection = transform.Find("JumpDetection").GetComponent<JumpDetectionComponent>();
    }
	
	void Update () {
		if (controlled)
        {
            float h = Input.GetAxisRaw("Horizontal");
            r.velocity = new Vector2(h * SPEED, 0);

            if (Input.GetAxisRaw("Vertical") > 0)
            {
                if (jumpDetection.canJump || jumpJuice > 0)
                {
                    jumpDetection.canJump = false;
                    jumpJuice -= Time.deltaTime;
                    r.velocity = new Vector2(r.velocity.x, JUMP * (jumpJuice / JUMP_DURATION));
                }
            } else if (jumpDetection.canJump)
            {
                jumpJuice = JUMP_DURATION; 
            }
        }
	}

    public void ToggleControlled()
    {
        this.controlled = !this.controlled;
    }

    // Normally unused..?
    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.name == "Goal")
        {
            gameController.Victory();
        } else if (collision.gameObject.name == "SecretGoal")
        {
            StartCoroutine(SuperVictory(collision.gameObject.transform));
        }
    }

    void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject.name == "Goal")
        {
            gameController.Victory();
        }
        else if (collider.gameObject.name == "SecretGoal")
        {
            StartCoroutine(SuperVictory(collider.gameObject.transform));
        }
    }

    IEnumerator SuperVictory(Transform target)
    {
        if (!victory)
        {
            victory = true;
            GameObject prefab = GameObject.Find("Civilian");
            for (int i = 0; i < 10; i++)
            {
                GameObject newCiv = Instantiate(prefab, target.position + new Vector3(Random.Range(2f, 6f), 5, 0), Quaternion.identity, target);
                newCiv.transform.localScale = 0.25f * new Vector3(1 / newCiv.transform.parent.localScale.x, 1 / newCiv.transform.parent.localScale.y, 1 / newCiv.transform.parent.localScale.z);
                yield return new WaitForSeconds(0.5f);
            }
            yield return new WaitForSeconds(0.5f);
            gameController.Victory();
        }
    }
}
